package com.df.my_net_game.game_rpc;

import com.baidu.bjf.remoting.protobuf.Codec;
import com.baidu.bjf.remoting.protobuf.ProtobufProxy;
import com.baidu.bjf.remoting.protobuf.annotation.ProtobufClass;
import io.netty.buffer.*;
import lombok.Data;

import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;

@ProtobufClass
@Data
public class GRpcHeader {
    private Integer cmdId = 0;
    //from
    //to
    private Integer reqFrom = 0;//客户端类型 0玩家客户端 1serverNode客户端
    private Integer msgType  = 1;//0 请求 ；1响应
    //包含消息的唯一id，消息序列号
    MsgMeta meta = null;

    public int lenth(){
        return 28;
    }

    public byte[] tobytes(){
        ByteBuf bb = null;
        try {
            int len = 4+12;
            byte[] encode = null;
            if(meta!=null){

                Codec<MsgMeta> msgMetaCodec = ProtobufProxy.create(MsgMeta.class);
                encode = msgMetaCodec.encode(meta);
                len+=encode.length;
            }
            bb = PooledByteBufAllocator.DEFAULT.buffer(len,len);
            bb.writeInt(len);
            bb.writeInt(cmdId);
            bb.writeInt(reqFrom);
            bb.writeInt(msgType);
            if(encode!=null){
                bb.writeBytes(encode);
            }
            byte[] bytes = new byte[bb.readableBytes()];
            bb.readBytes(bytes);
            return bytes;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }finally {
            bb.release();
        }
    }

    public void readFromBytes(byte[] bytes){
        ByteBuffer wrap = ByteBuffer.wrap(bytes);

        try {

//            reqId = bb.readLong();
            this.cmdId = wrap.getInt();
            reqFrom = wrap.getInt();
            msgType = wrap.getInt();
            if(bytes.length>12){
                byte[] metaBytes = new byte[bytes.length-12];
                wrap.get(metaBytes);
                Codec<MsgMeta> msgMetaCodec = ProtobufProxy.create(MsgMeta.class);
                MsgMeta decode = msgMetaCodec.decode(metaBytes);
                meta = decode;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
        }
    }

    public void addHeader(String key,String value){
        if(meta==null){
            meta = new MsgMeta();
        }
        meta.getMeta().put(key,value);
    }
}
